{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "958bc1a1-7df0-4144-b664-aeefe5a5a9c7",
   "metadata": {},
   "source": [
    "# langchain agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "f7fa0e62-f078-4bea-b002-41f61ea9a701",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import relevant functionality\n",
    "#from langchain_anthropic import ChatAnthropic\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langgraph.checkpoint.memory import MemorySaver\n",
    "from langgraph.prebuilt import create_react_agent\n",
    "\n",
    "# Create the agent\n",
    "memory = MemorySaver()\n",
    "model = ChatOpenAI(\n",
    "   openai_api_key=\"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\",\n",
    "  openai_api_base=\"https://openrouter.ai/api/v1\",\n",
    "  model_name = \"mistralai/mistral-small-3.1-24b-instruct:free\"\n",
    "  )\n",
    "# search model by selet tools and find mistralai\n",
    "from langchain_core.tools import tool\n",
    "@tool\n",
    "def search(query: str):\n",
    "    \"\"\"Call to surf the web.\"\"\"\n",
    "    if \"sf\" in query.lower() or \"san francisco\" in query.lower():\n",
    "        return \"It's 60 degrees and foggy.\"\n",
    "    return \"It's 90 degrees and sunny.\"\n",
    "\n",
    "\n",
    "@tool    \n",
    "def add(a: int, b: int) -> int:\n",
    "    \"\"\"Add two integers.\n",
    "    \"\"\"\n",
    "    return a + b\n",
    "\n",
    "@tool\n",
    "def multiply(a: int, b: int) -> int:\n",
    "    \"\"\"Multiply two integers.\n",
    "\n",
    "    Args:\n",
    "        a: First integer\n",
    "        b: Second integer\n",
    "    \"\"\"\n",
    "    return a * b\n",
    "    \n",
    "tools = [search, add, multiply]\n",
    "model_with_tools = model.bind_tools(tools)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "f9a78dc3-c23f-4473-9c3e-55c7a7dfbffa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ContentString: Hello! How can I assist you today? If you're looking for web browsing, you can ask me to search for something, or if you need help with some calculations, just let me know! As of now, I can perform addition and multiplication of two integers.\n",
      "ToolCalls: []\n"
     ]
    }
   ],
   "source": [
    "response = model_with_tools.invoke([HumanMessage(content=\"Hi!\")])\n",
    "\n",
    "print(f\"ContentString: {response.content}\")\n",
    "print(f\"ToolCalls: {response.tool_calls}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "74aa6f56-5ac6-4cd0-bb7c-52e37c9cb4f5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
      "\n",
      "The sum of 23 and 32 is 55. If you want me to add these numbers I need to call the addition tool for that. Do you want me to proceed?\n"
     ]
    }
   ],
   "source": [
    "response = model_with_tools.invoke([HumanMessage(content=\"What's 23 + 32?\")])\n",
    "\n",
    "#print(f\"ContentString: {response.content}\")\n",
    "#print(f\"ToolCalls: {response.tool_calls}\")\n",
    "response.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "f2dbe050-ca8c-48ba-bb21-f47e650181e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langgraph.prebuilt import create_react_agent\n",
    "\n",
    "agent_executor = create_react_agent(model, tools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "2d311a7a-e523-46b9-9adf-89aebf58e34a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='hi!', additional_kwargs={}, response_metadata={}, id='fe7f02ec-e6ea-4066-a11e-70c8aa06b30a'),\n",
       " AIMessage(content='Hello! How can I assist you today?', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 62, 'total_tokens': 72, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'mistralai/mistral-small-3.1-24b-instruct', 'system_fingerprint': None, 'id': 'gen-1743412195-LpzhM9DoLg2vYBLtxqiE', 'finish_reason': 'stop', 'logprobs': None}, id='run-b6285997-c0fd-4de2-97e6-f0050adfdbf7-0', usage_metadata={'input_tokens': 62, 'output_tokens': 10, 'total_tokens': 72, 'input_token_details': {}, 'output_token_details': {}})]"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = agent_executor.invoke({\"messages\": [HumanMessage(content=\"hi!\")]})\n",
    "response[\"messages\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "b924fe20-c94b-4fe7-887e-88c66b198bcf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='whats the weather in sf?', additional_kwargs={}, response_metadata={}, id='61afc58f-678b-4a43-8e88-14bc74ca0e4c'),\n",
       " AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'dKhQaBzAv', 'function': {'arguments': '{\"query\": \"weather in san francisco\"}', 'name': 'search'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 24, 'prompt_tokens': 67, 'total_tokens': 91, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'mistralai/mistral-small-3.1-24b-instruct', 'system_fingerprint': None, 'id': 'gen-1743415381-mOPj4UniQePsnOBxCsev', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-ecbf8d6d-bc5b-47ce-8181-efb28d51bc12-0', tool_calls=[{'name': 'search', 'args': {'query': 'weather in san francisco'}, 'id': 'dKhQaBzAv', 'type': 'tool_call'}], usage_metadata={'input_tokens': 67, 'output_tokens': 24, 'total_tokens': 91, 'input_token_details': {}, 'output_token_details': {}}),\n",
       " ToolMessage(content=\"It's 60 degrees and foggy.\", name='search', id='064b9b5f-44bc-4601-a45a-98d5e95933d7', tool_call_id='dKhQaBzAv'),\n",
       " AIMessage(content='It looks like the current weather in San Francisco is 60 degrees with foggy conditions.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 20, 'prompt_tokens': 123, 'total_tokens': 143, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'mistralai/mistral-small-3.1-24b-instruct', 'system_fingerprint': None, 'id': 'gen-1743415384-dStstu8qSICLfzONP78i', 'finish_reason': 'stop', 'logprobs': None}, id='run-d201dd51-d4f9-4c78-bb63-bf688e4e06ee-0', usage_metadata={'input_tokens': 123, 'output_tokens': 20, 'total_tokens': 143, 'input_token_details': {}, 'output_token_details': {}})]"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = agent_executor.invoke(\n",
    "    {\"messages\": [HumanMessage(content=\"whats the weather in sf?\")]}\n",
    ")\n",
    "response[\"messages\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "753cbb4d-7e57-4702-98bd-87de576e3ba5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[HumanMessage(content='what is 233 + 322?', additional_kwargs={}, response_metadata={}, id='ac979434-ce95-4652-a8b2-25e612744518'),\n",
       " AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'M8JeKsTYR', 'function': {'arguments': '{\"a\": 23, \"b\": 322{\"a\": 233, \"b\": 322}', 'name': 'add'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 29, 'prompt_tokens': 236, 'total_tokens': 265, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'mistralai/mistral-small-3.1-24b-instruct', 'system_fingerprint': None, 'id': 'gen-1743415565-xWH6oa5sLmgzqIkLuolT', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-19250f25-9e65-4cf1-a624-c29bf9a5ce73-0', invalid_tool_calls=[{'name': 'add', 'args': '{\"a\": 23, \"b\": 322{\"a\": 233, \"b\": 322}', 'id': 'M8JeKsTYR', 'error': 'Function add arguments:\\n\\n{\"a\": 23, \"b\": 322{\"a\": 233, \"b\": 322}\\n\\nare not valid JSON. Received JSONDecodeError Expecting \\',\\' delimiter: line 1 column 19 (char 18)\\nFor troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE ', 'type': 'invalid_tool_call'}], usage_metadata={'input_tokens': 236, 'output_tokens': 29, 'total_tokens': 265, 'input_token_details': {}, 'output_token_details': {}})]"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = agent_executor.invoke(\n",
    "    {\"messages\": [HumanMessage(content=\"what is 233 + 322?\")]}\n",
    ")\n",
    "response[\"messages\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab5c5f2b-88d2-4891-a6e9-3da28db4ddf0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
